import { StateCreator } from 'zustand'
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'

// 创建持久化存储的包装器
export const createPersistStoreWithOptions = <T extends object>(
  name: string,
  config: {
    initialState: Partial<T>;
    partialize?: (state: T) => Partial<T>;
    version?: number;
    migrate?: (persistedState: any, version: number) => T;
  },
  stateCreator: StateCreator<T, [], []>
) => {
  const {
    initialState,
    partialize,
    version = 1,
    migrate
  } = config;
  
  return create<T>()(
    devtools(
      persist(stateCreator, {
        name: `novelai-${name}`,
        partialize,
        version,
        migrate,
        onRehydrateStorage: () => (state) => {
          if (state) {
            console.log(`State "${name}" rehydrated successfully`);
          } else {
            console.error(`Failed to rehydrate state "${name}"`);
          }
        }
      })
    )
  );
};

// 常用的持久化配置
export const commonPersistConfig = {
  // 默认过滤掉加载状态和错误信息
  partialize: (state: any) => {
    const result = { ...state };
    delete result.isLoading;
    delete result.isSending;
    delete result.error;
    return result;
  },
  
  // 版本转换
  migrate: (persistedState: any, version: number) => {
    if (version === 1) {
      return persistedState;
    }
    // 未来可以在这里添加版本迁移逻辑
    return persistedState;
  }
}; 